﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Linq;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Dimok;
using Dimok.Exceptions;
using Data.LINQ;
using Jr = Jayrock.Json.Conversion.JsonConvert;

[Serializable]
internal class Error {
	public string message { get; set; }
	public Error(string message) {
		this.message = message;
	}
}

public partial class Manager_Common_AttachDocument : System.Web.UI.Page {
	protected void Page_Load(object sender, EventArgs e) {
		string message = "";
		if (Request.Files.Count > 0) {
			byte[] file = new byte[Request.Files[0].InputStream.Length];
			Request.Files[0].InputStream.Read(file, 0, (int)Request.Files[0].InputStream.Length);
			var mb = new MotoBank();
			try {
				var fileName = Request["hdnFileName"];
				if ((fileName +"")== "") throw new Exception("FileName is empty.");
				if (Path.GetExtension(fileName) == "") throw new Exception("File Name has some illigal characters or has no extention.");
				var guidDocs = Request["hdnGuidDocs"];
				var t = new t_Document() { Body = null, GUID_Table = new Guid(), Name = "", ContentType = "" };
				string contentType = Dimok.Images.Enums.GetContentType(file) ;
				contentType =  Request.Files[0].ContentType;
				mb.t_Documents.Insert(new { Body = file, GUID_Table = new Guid(guidDocs), Name = fileName, ContentType = contentType });
			} catch (Exception exc) {
				ASPException.Publish(exc);
				message = this.Server.UrlPathEncode(ASPException.GetMessages(exc));
			}
			Response.Clear();
			Response.Write(Jr.ExportToString(new Error(message).ToDictionary()));
			Response.End();
		}

	}
}
